package com.project.filter;

import org.apache.catalina.Context;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.取出session中保存的登陆信息
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        Object loginObj=req.getSession().getAttribute("loginUser");
        HttpServletResponse resp=(HttpServletResponse) servletResponse;

        if(loginObj==null){//如果登陆信息为空，则为非法用户

            resp.getWriter().print("noLogin");
        }else {
            //请求通过过滤器，允许继续访问目标资源
            filterChain.doFilter(req,resp);
        }
    }


//    /**
//     * 3.注册过滤器
//     */
//    private void registerFilter(Filter filter, String urlPattern, Context context){
//        FilterDef fd1=new FilterDef();
//        fd1.setFilter(filter);//设置过滤器
//        fd1.setFilterName(filter.getClass().getSimpleName());//设置过滤器名称
//
//        FilterMap fm1=new FilterMap();
//        fm1.setFilterName(filter.getClass().getSimpleName());
//        fm1.addURLPattern(urlPattern);//设置过滤器范围
//
//        context.addFilterDef(fd1);
//        context.addFilterMap(fm1);
//    }

//       this.registerFilter(new AddSpeakFilter(),"/speak/add",context);

}
